﻿using _111.Models;
using Dapper;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using MyDapperApi.Models;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using QYWXUpdate.DataModel;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Text.Json.Nodes;

namespace MyDapperApi.Services.Auth;

public class AuthService : IAuthService
{
    private readonly IConfiguration _configuration;
    private readonly IHttpClientFactory _httpClientFactory;

    // 通过依赖注入获取配置，从而读取连接字符串
    public AuthService(IHttpClientFactory httpClientFactory, IConfiguration configuration)
    {
        _configuration = configuration;
        _httpClientFactory = httpClientFactory;
    }

    // 生成JWT令牌
    public string GenerateToken(string username, IEnumerable<string> roles = null)
    {
        // 1. 创建声明
        var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, username),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

        // 添加角色声明
        if (roles != null)
        {
            foreach (var role in roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }
        }

        // 2. 获取密钥和加密算法
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(
            _configuration["JwtSettings:SecretKey"]));
        var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        // 3. 设置令牌过期时间
        var expires = DateTime.Now.AddMinutes(
            Convert.ToDouble(_configuration["JwtSettings:ExpiresInMinutes"]));

        // 4. 创建令牌
        var token = new JwtSecurityToken(
            issuer: _configuration["JwtSettings:Issuer"],
            audience: _configuration["JwtSettings:Audience"],
            claims: claims,
            expires: expires,
            signingCredentials: credentials
        );

        // 5. 返回序列化的令牌
        return new JwtSecurityTokenHandler().WriteToken(token);
    }

    // 验证JWT令牌并返回声明
    public ClaimsPrincipal ValidateToken(string token)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.UTF8.GetBytes(_configuration["JwtSettings:SecretKey"]);

        try
        {
            var principal = tokenHandler.ValidateToken(token, new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = true,
                ValidIssuer = _configuration["JwtSettings:Issuer"],
                ValidateAudience = true,
                ValidAudience = _configuration["JwtSettings:Audience"],
                ValidateLifetime = true, // 验证过期时间
                ClockSkew = TimeSpan.Zero // 不允许时间偏移
            }, out var validatedToken);

            return principal;
        }
        catch
        {
            // 令牌验证失败
            return null;
        }
    }

    public async Task<CommonResponse> CreateToken(string role,string name)
    {
        var result = new CommonResponse();
        var roles = new List<string> { role };
        var token = GenerateToken(name, roles);
        result.SetSuccess(token);
        return result;
    }

    public async Task<CommonResponse> CheckToken(IdRequest request)
    {
        var result = new CommonResponse();

        var res = ValidateToken(request.Id);
        result.SetSuccess(res);

        return result;
    }
}